// axios封装
import axios from 'axios'
import { getToken, setToken } from '@/utils'
import { clearUserInfo, removeToken } from '@/store/modules/user'
import { useRoutes, useRo } from 'react-router-dom'
import router from '@/router'

// 1.根域名配置
// 2.超时时间
// 3.请求拦截器，响应拦截器

const request = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 5000
})

request.interceptors.request.use(config => {
    // 请求拦截器
    const token = getToken()
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, error => {
    return Promise.reject(error)
})

request.interceptors.response.use(response => {
    // 2xx范围内的状态码都会触发该函数
    return response.data
}, error => {
    // 超出 2xx 范围的状态码都会触发该函数
    const res = error.response;
    if (res.status === 401) {
        clearUserInfo();
        router.navigate('/login')
        window.location.reload();
    }
    return Promise.reject(error)
})

export {
    request
}